package com.pace.ribbon.asyn.pool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class AsyncExecutePool implements AsyncConfigurer {

    private Logger logger = LoggerFactory.getLogger(AsyncExecutePool.class);

    @Autowired
    private SimpleThreadPoolConfig simpleThreadPoolConfig;


    @Override
    public Executor getAsyncExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(simpleThreadPoolConfig.getCorePoolSize());
        executor.setMaxPoolSize(simpleThreadPoolConfig.getMaxPoolSize());
        executor.setKeepAliveSeconds(simpleThreadPoolConfig.getKeepAliveSeconds());
        executor.setQueueCapacity(simpleThreadPoolConfig.getQueueCapacity());
        executor.setThreadNamePrefix(simpleThreadPoolConfig.getThreadNamePrefix());
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        executor.initialize();

        logger.debug("线程池初始化完成");

        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
                logger.debug("异常："+throwable+throwable.getMessage()+method.getName());
            }
        };
    }


}
